<template>
	<view class="container">
		<!-- 订阅消息授权引导 -->
		<view v-if="showSubscribeGuide" class="subscribe-guide">
			<view class="guide-content">
				<text class="guide-title">开启消息通知</text>
				<text class="guide-desc">及时获取工单状态更新提醒，不错过任何重要信息</text>
				<view class="guide-btns">
					<button class="cancel-btn" @click="showSubscribeGuide = false">暂不开启</button>
					<button class="confirm-btn" @click="handleSubscribeAuth">立即开启</button>
				</view>
			</view>
		</view>

		<view class="tab-bar">
			<view v-for="(item, index) in tabList" :key="index" class="tab-item" :class="{ active: current === index }"
				@click="onTabClick(index)">
				{{ item.name }}
			</view>
		</view>

		<!-- 当选中“进行中”时显示状态选项（已删除待审批） -->
		<view v-if="current === 0" class="status-filter">
			<view style="margin:10px 15px;font-size:16px;">状态</view>
			<view class="status">
				<view v-for="(status, statusIndex) in statusList" :key="statusIndex" class="status-item"
					:class="{ active: activeStatus === statusIndex }" @click="changeStatus(statusIndex)"
					hover-class="none">
					{{ status }}
				</view>
			</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-bar">
			<input type="text" placeholder="输入位置、对象、描述" v-model="searchKeyword" @input="onSearch" />
		</view>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 加载中状态 -->
			<view v-if="isLoading" class="loading">
				<uni-loading-icon size="24" color="#2BA245"></uni-loading-icon>
				<text>加载中...</text>
			</view>

			<!-- 空状态 -->
			<view v-else-if="filteredOrders.length === 0" class="empty-state">
				<image src="/static/wrench.png"></image>
				<text>亲，当前暂无符合条件的工单</text>
				<button @click="createReport">报单</button>
			</view>

			<!-- 工单列表 -->
			<view v-else class="order-list">
				<view class="order-item" v-for="order in filteredOrders" :key="order.id">
					<!-- 顶部：工单编号 + 状态标签 -->
					<view class="order-header flex justify-between items-center mb-3">
						<text class="order-number text-xs text-gray-500">工单编号：{{ order.orderNumber }}</text>
						<!-- 工单状态标签 -->
						<text
							:class="'order-status px-2 py-1 rounded-md text-xs font-medium ' + getStatusClass(order.status)">{{ getDisplayStatus(order.status) }}</text>
					</view>

					<!-- 标题行 -->
					<view class="order-title font-bold text-lg mb-2">{{ order.title }}</view>

					<!-- 基本信息行 -->
					<view class="order-info flex flex-wrap gap-x-10 gap-y-2 text-sm text-gray-600 mb-3">
						<view class="flex items-center">
							<uni-icon type="map-pin" size="14" color="#999" class="mr-1" />
							<text>{{ order.unit || '无单位信息' }}</text>
						</view>
						<view class="flex items-center">
							<uni-icon type="navigation" size="14" color="#999" class="mr-1" />
							<text>{{ order.location }}</text>
						</view>
					</view>

					<!-- 描述信息 -->
					<view class="order-desc text-sm text-gray-600 mb-3" v-if="order.description">
						<text class="text-gray-500">描述：</text>
						<text>{{ order.description }}</text>
					</view>

					<!-- 底部：时间 + 来源 + 联系人 + 接单按钮 -->
					<view class="order-meta-container">
						<view class="order-meta">
							<text class="flex items-center">
								<uni-icon type="time" size="14" color="#999" class="mr-1" />
								{{ formatTime(order.reportTime) }}
							</text>
							<text>{{ order.source }}</text>
							<text class="flex items-center">
								<uni-icon type="phone" size="14" color="#999" class="mr-1" />
								{{ order.reporterName }}({{ order.reporterPhone }})
							</text>
						</view>

						<!-- 接单按钮 - 只在待处理状态显示 -->
						<view v-if="order.status === '0'" class="order-actions">
							<button class="accept-order-btn" @click="handleAcceptOrder(order)">
								接单处理
							</button>
						</view>
					</view>

					<!-- 点击查看详情的区域 -->
					<view class="clickable-area" @click="goToOrderDetail(order)"></view>
				</view>
			</view>
		</view>

		<!-- 关闭订阅确认弹窗 -->
		<view v-if="showCloseConfirm" class="confirm-modal">
			<view class="modal-content">
				<text class="modal-title">关闭消息订阅？</text>
				<text class="modal-desc">关闭后将无法接收工单状态更新提醒，是否确认？</text>
				<view class="modal-btns">
					<button class="modal-cancel" @click="showCloseConfirm = false">取消</button>
					<button class="modal-confirm" @click="confirmCloseSubscribe">确认关闭</button>
				</view>
			</view>
		</view>

		<!-- 接单确认弹窗 -->
		<view v-if="showAcceptConfirm" class="confirm-modal">
			<view class="modal-content">
				<text class="modal-title">确认接单</text>
				<text class="modal-desc">您确定要接取此工单吗？接单后将负责该工单的处理。</text>
				<view class="modal-btns">
					<button class="modal-cancel" @click="showAcceptConfirm = false">取消</button>
					<button class="modal-confirm" @click="confirmAcceptOrder">确认接单</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getBaoDanList,
		getjieDanList // 导入接单接口
	} from "./baodan.js"

	import {
		formatTime
	} from "../../utils/formatTimeAndSort.js"

	export default {
		data() {
			return {
				// 标签页调整：将“待评价”改为“已驳回”
				tabList: [{
						name: '进行中'
					},
					{
						name: '已驳回'
					},
					{
						name: '已完成'
					},
					{
						name: '已终止'
					}
				],
				current: 0,
				// 状态筛选列表：删除“待审批”，保留4项
				statusList: ['全部', '待处理', '处理中', '待验收'],
				activeStatus: 0,
				searchKeyword: '',
				isLoading: false,
				orders: [],
				showSubscribeGuide: false,
				subscribeStatus: null,
				getOrdersInterval: null,
				showCloseConfirm: false,
				showAcceptConfirm: false,
				currentOrder: null,
				appid: 'wxebf23a5019f0b2aa',
				secret: '',
				token: '',
				isDev: true
			};
		},
		onLoad() {
			try {
				this.initSubscribeStatus();
				this.fetchOrders();
			} catch (error) {
				console.error('页面加载失败', error);
			}
		},
		onShow() {
			// 每次页面显示时重新获取工单列表，确保数据是最新的
			this.fetchOrders();
		},
		computed: {
			filteredOrders() {
				const statusFilter = this.tabList[this.current].name;
				const result = this.orders.filter(order => {
					const statusMatch = this.matchStatus(order, statusFilter);
					const keywordMatch = this.searchKeyword === '' ||
						(order.title && order.title.includes(this.searchKeyword)) ||
						(order.description && order.description.includes(this.searchKeyword)) ||
						(order.location && order.location.includes(this.searchKeyword));
					return statusMatch && keywordMatch;
				});
				console.log('过滤后的工单：', result);
				return result;
			}
		},
		methods: {
			async initSubscribeStatus() {
				try {
					// 获取微信小程序权限设置
					const settingRes = await uni.getSetting();
					// 关键修复：确保 authSetting 是对象（若不存在则初始化为空对象）
					const authSetting = settingRes.authSetting || {};

					// 订阅消息模板 ID
					const templateId = 'N1BgeMNFfZCjVFhUYL0mce1fpOxyitrp4Al-i8MX2r8';
					// 安全访问权限状态（先判断 authSetting 存在，再访问具体权限）
					const hasAuth = authSetting[`scope.subscribeMessage.${templateId}`];

					// 根据实时权限更新状态
					if (hasAuth === true) {
						this.subscribeStatus = 'accept';
						uni.setStorageSync('subscribeStatus', 'accept');
					} else if (hasAuth === false) {
						this.subscribeStatus = 'reject';
						uni.setStorageSync('subscribeStatus', 'reject');
					} else {
						// 从未授权过（hasAuth 为 undefined）
						this.subscribeStatus = null;
					}
					this.showSubscribeGuide = this.subscribeStatus === null;
				} catch (error) {
					console.error('获取权限设置失败', error);
					// 异常时回退到本地存储
					const storedStatus = uni.getStorageSync('subscribeStatus');
					this.subscribeStatus = storedStatus || null;
					this.showSubscribeGuide = !storedStatus;
				}
			},

			toggleSubscribeSetting() {
				if (this.subscribeStatus === 'accept') {
					this.showCloseConfirm = true;
				} else {
					this.showSubscribeGuide = true;
				}
			},

			handleSubscribeAuth() {
				this.showSubscribeGuide = false;
				uni.requestSubscribeMessage({
					tmplIds: ['N1BgeMNFfZCjVFhUYL0mce1fpOxyitrp4Al-i8MX2r8'],
					success: (res) => {
						const templateId = 'N1BgeMNFfZCjVFhUYL0mce1fpOxyitrp4Al-i8MX2r8';
						if (res[templateId] === 'accept') {
							this.subscribeStatus = 'accept';
							uni.showToast({
								title: '消息通知已开启',
								icon: 'success'
							});
						} else if (res[templateId] === 'reject') {
							this.subscribeStatus = 'reject';
							uni.showToast({
								title: '已拒绝消息通知，可前往设置重新开启',
								icon: 'none'
							});
						}
						uni.setStorageSync('subscribeStatus', this.subscribeStatus);
					},
					fail: (err) => {
						console.error('订阅授权失败', err);
						if (err.errCode === 20004) {
							this.subscribeStatus = 'reject';
							uni.setStorageSync('subscribeStatus', 'reject');
							uni.showToast({
								title: '已拒绝消息通知，可前往设置重新开启',
								icon: 'none'
							});
						} else {
							uni.showToast({
								title: '授权失败，请稍后重试',
								icon: 'none'
							});
						}
					}
				});
			},

			confirmCloseSubscribe() {
				this.subscribeStatus = 'reject';
				uni.setStorageSync('subscribeStatus', 'reject');
				this.showCloseConfirm = false;
				uni.showToast({
					title: '已关闭消息订阅功能',
					icon: 'success'
				});
			},

			onTabClick(index) {
				this.current = index;
				if (index !== 0) this.activeStatus = 0;
			},

			changeStatus(index) {
				this.activeStatus = index;
			},

			createReport() {
				uni.navigateTo({
					url: '/life/repair/repair'
				});
			},

			goToOrderDetail(order) {
				// 子状态调整：删除待审批（原索引3），当前子状态仅0-3
				const subStatus = this.current === 0 ? this.activeStatus : null;
				const orderStr = encodeURIComponent(JSON.stringify({
					...order,
					subStatus
				}));
				uni.navigateTo({
					url: `/life/repairDetail/repairDetail?order=${orderStr}`
				});
			},

			matchStatus(order, statusFilter) {
				console.log('工单筛选：', '标签页=', statusFilter, '状态码=', order.status, '子状态索引=', this.activeStatus);
				// 新状态映射：大标签页与状态码对应关系
				const statusMap = {
					'进行中': ['0', '1', '2'], // 包含待处理、处理中、待验收（删除原3=待审批）
					'已驳回': ['4', '7'], // 合并已驳回的两个状态码
					'已完成': ['3'], // 已完成对应status=3
					'已终止': ['5']
				};

				// 先过滤大标签
				if (!statusMap[statusFilter]?.includes(order.status)) {
					return false;
				}

				// 处理“进行中”的子状态筛选（删除待审批后，子状态索引对应关系）
				if (statusFilter === '进行中') {
					const indexToStatus = [
						['0', '1', '2'], // 0:全部（进行中包含的所有状态）
						['0'], // 1:待处理（仅status=0）
						['1'], // 2:处理中（仅status=1）
						['2'] // 3:待验收（仅status=2）
					];
					return indexToStatus[this.activeStatus].includes(order.status);
				}

				return true;
			},

			// 状态文本显示：使用新的状态映射
			getDisplayStatus(status) {
				const statusTextMap = {
					'0': '待处理',
					'1': '处理中',
					'2': '待验收',
					'3': '已完成',
					'4': '已驳回',
					'5': '已终止',
					'7': '已驳回'
				};
				return statusTextMap[status] || `状态码: ${status}`;
			},

			// 状态样式：适配新状态
			getStatusClass(status) {
				const classMap = {
					'0': 'status-pending', // 待处理：橙色
					'1': 'status-processing', // 处理中：蓝色
					'2': 'status-pending-review', // 待验收：黄色
					'3': 'status-completed', // 已完成：绿色
					'4': 'status-rejected', // 已驳回：红色
					'5': 'status-terminated', // 已终止：深红色
					'7': 'status-rejected' // 已驳回：红色（与4一致）
				};
				return classMap[status] || '';
			},

			formatTime(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`;
			},

			onSearch() {},

			async fetchOrders() {
				this.isLoading = true;
				try {
					const res = await getBaoDanList();
					console.log('fetchOrders：接口返回完整数据', res);

					if (res.success === true) {
						const rawOrders = Array.isArray(res.data.workorder) ? res.data.workorder : [];

						const orderList = rawOrders.map(item => {
							const statusTextMap = {
								'0': '待处理',
								'1': '处理中',
								'2': '待验收',
								'3': '待审批',
								'4': '已完成',
								'5': '已终止',
								'6': '待付款',
								'7': '待评价'
							};

							// 处理image字段（直接使用数组，不再解析JSON）
							const images = Array.isArray(item.image) ?
								item.image.filter(img => typeof img === 'string' && img.trim()) : [];

							// 处理successImage字段
							const successImage = Array.isArray(item.successImage) ?
								item.successImage.filter(img => typeof img === 'string' && img.trim()) : [];

							// 提取处理人信息
							const processorInfo = typeof item.processor === 'object' && item.processor !==
								null ?
								item.processor : {};

							// 计算处理时间
							const processStartTime = item.processStartTime ? new Date(item.processStartTime) :
								null;
							const processEndTime = item.processEndTime ? new Date(item.processEndTime) : null;
							let timeConsumed = null;

							if (processStartTime && processEndTime) {
								const diffMs = processEndTime - processStartTime;
								const hours = Math.floor(diffMs / 3600000);
								const minutes = Math.floor((diffMs % 3600000) / 60000);
								timeConsumed = hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
							}

							return {
								id: item.id,
								orderNumber: item.orderNumber,
								title: item.repairObject || `工单#${item.orderNumber}`,
								unit: item.unit,
								location: item.location || item.unit,
								description: item.description || '无描述',
								reportTime: item.reportTime || item.createdAt,
								reporterName: item.reporterName,
								reporterPhone: item.reporterPhone,
								source: item.source || '未知来源',
								status: item.status,
								evaluateDetails: item.evaluateDetails,
								evaluatetext: item.evaluatetext,
								starLevel: item.starLevel,
								processor: item.processor,
								statusText: statusTextMap[item.status] || `状态码: ${item.status}`,
								successtext: item.successtext,
								images: images,
								successImage: successImage,
								processorId: item.maintainerId,
								processorName: processorInfo.name || '未分配',
								processorPhone: processorInfo.phone || '',
								timeConsumed: timeConsumed || item.timeConsumed,
								createdAt: item.createdAt,
								updatedAt: item.updatedAt,
								enterpriseCode: item.EnterpriseCode || "GK001"
							};
						});

						this.orders = orderList;
						console.log('fetchOrders：工单数据更新成功', this.orders);
					} else {
						console.warn('fetchOrders：接口请求失败', res.msg || '未知错误');
					}
				} catch (error) {
					console.error('fetchOrders：请求异常', error);
				} finally {
					this.isLoading = false;
				}
			},


			showOrderUpdateToast(order) {
				uni.showToast({
					title: `工单${order.id}状态更新为${order.statusText}`,
					icon: 'none',
					duration: 3000
				});
			},

			handleAcceptOrder(order) {
				this.currentOrder = order;
				this.showAcceptConfirm = true;
			},

			async confirmAcceptOrder() {
				if (!this.currentOrder) return;
				this.showAcceptConfirm = false;
				try {
					uni.showLoading({
						title: '提交中...'
					});
					const res = await getjieDanList(this.currentOrder.id);
					if (res.success) {
						uni.showToast({
							title: '接单成功',
							icon: 'success'
						});
						this.fetchOrders(); // 刷新列表
					} else {
						uni.showToast({
							title: res.msg || '接单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('接单接口异常', error);
					uni.showToast({
						title: '接单失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			closeDetailPageIfOpen() {
				const pages = getCurrentPages();
				for (let i = pages.length - 1; i >= 0; i--) {
					if (pages[i].route.includes('repairDetail')) {
						uni.navigateBack({
							delta: pages.length - i - 1
						});
						break;
					}
				}
			}
		}
	};
</script>

<style scoped>
	/* 基础样式与布局 */
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 公共容器样式 */
	.subscribe-setting,
	.status-filter,
	.search-bar,
	.order-list {
		background-color: white;
		margin-bottom: 10px;
	}

	/* 订阅相关样式 */
	.subscribe-setting {
		padding: 10px 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
	}

	.setting-btn {
		font-weight: bold;
	}

	/* 模态框与引导层 */
	.subscribe-guide,
	.confirm-modal {
		position: fixed;
		inset: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.subscribe-guide {
		z-index: 999;
	}

	.confirm-modal {
		z-index: 1000;
	}

	.guide-content,
	.modal-content {
		width: 80%;
		padding: 30rpx;
		background-color: white;
		border-radius: 16rpx;
		text-align: center;
	}

	.guide-title,
	.modal-title {
		display: block;
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
	}

	.guide-title {
		font-size: 20px;
	}

	.modal-title {
		font-size: 18px;
		margin-bottom: 15px;
	}

	.guide-desc,
	.modal-desc {
		display: block;
		font-size: 14px;
		color: #666;
		line-height: 1.5;
		margin-bottom: 30rpx;
	}

	.modal-desc {
		margin-bottom: 25px;
	}

	.guide-btns,
	.modal-btns {
		display: flex;
		justify-content: space-around;
	}

	.cancel-btn,
	.confirm-btn,
	.modal-cancel,
	.modal-confirm {
		border-radius: 8rpx;
	}

	/* 标签栏样式 */
	.tab-bar {
		display: flex;
		border-bottom: 1px solid #eee;
		background-color: white;
	}

	.tab-item {
		flex: 1;
		padding: 10px;
		font-size: 16px;
		color: #999;
		text-align: center;
	}

	.tab-item.active {
		color: #2BA245;
		border-bottom: 2px solid #2BA245;
		font-weight: bold;
	}

	/* 状态筛选器 */
	.status-filter>view:first-child {
		margin: 10px 15px;
		font-size: 16px;
	}

	.status {
		display: flex;
		justify-content: space-around;
		padding: 10px 0;
	}

	.status-item {
		padding: 5px 15px;
		font-size: 14px;
		color: #666;
		background-color: #f5f5f5;
		border-radius: 20px;
	}

	.status-item.active {
		color: white;
		background-color: #2BA245;
		font-weight: bold;
	}

	/* 搜索栏 */
	.search-bar {
		padding: 10px;
		box-sizing: border-box;
	}

	.search-bar input {
		width: 100%;
		height: 40px;
		line-height: 40px;
		padding: 0 15px;
		font-size: 14px;
		color: #333;
		background-color: #f5f5f5;
		border: none;
		border-radius: 20px;
		box-sizing: border-box;
	}

	/* 主内容区 */
	.main-content {
		padding: 10px;
	}

	/* 加载与空状态 */
	.loading {
		padding: 20px;
		text-align: center;
	}

	.empty-state {
		min-height: 300px;
		padding: 20px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.empty-state image {
		width: 100px;
		height: 100px;
		margin-bottom: 15px;
	}

	.empty-state text {
		margin-bottom: 20px;
		color: #999;
	}

	.empty-state button {
		width: 180px;
		height: 40px;
		line-height: 40px;
		font-size: 16px;
		color: white;
		background-color: #2BA245;
		border-radius: 20px;
	}

	/* 工单列表 */
	.order-list {
		border-radius: 10px;
		overflow: hidden;
	}

	.order-item {
		position: relative;
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.order-item:active {
		background-color: #f9f9f9;
	}

	/* 工单头部 */
	.order-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.order-number {
		font-size: 12px;
		color: #666;
	}

	.order-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	/* 工单状态标签 */
	.order-status {
		padding: 2px 8px;
		font-size: 12px;
		border-radius: 4px;
		color: white;
	}

	/* 状态颜色（新增已驳回样式） */
	.status-pending {
		background-color: #FF9800;
	}

	.status-processing {
		background-color: #2196F3;
	}

	.status-pending-review {
		background-color: #FFC107;
	}

	.status-completed {
		background-color: #2BA245;
	}

	.status-terminated {
		background-color: #F44336;
	}

	/* 新增：已驳回状态颜色 */
	.status-rejected {
		background-color: #E53E3E;
	}

	/* 工单信息区 */
	.order-info {
		display: flex;
		flex-wrap: wrap;
		gap: 15px 20px;
		font-size: 14px;
		color: #666;
	}

	.order-desc {
		font-size: 14px;
		line-height: 1.5;
		padding-left: 2px;
		margin-bottom: 10px;
	}

	/* 工单元信息与操作按钮 */
	.order-meta-container {
		position: relative;
	}

	.order-meta {
		display: flex;
		justify-content: space-between;
		font-size: 12px;
		color: #999;
		padding-right: 120px;
	}

	/* 接单按钮 */
	.order-actions {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		z-index: 2;
	}

	.accept-order-btn {
		width: 100px;
		height: 32px;
		line-height: 32px;
		font-size: 14px;
		color: #fff;
		background-color: #1677ff;
		border-radius: 4px;
		padding: 0;
	}

	.accept-order-btn:active {
		background-color: #0958d9;
	}

	/* 点击区域 */
	.clickable-area {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
	}
</style>